#!/usr/bin/env python3
"""
诊断Shopify API连接问题
"""

import os
import sys
import logging

# 添加当前目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

# 直接导入需要的模块
import shopify
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()

# 获取配置
def get_shopify_config():
    """获取Shopify配置"""
    return {
        'api_key': os.getenv("SHOPIFY_API_KEY", ""),
        'api_secret': os.getenv("SHOPIFY_API_SECRET", ""),
        'store_url': os.getenv("SHOPIFY_STORE_URL", ""),
        'access_token': os.getenv("SHOPIFY_ACCESS_TOKEN", "")
    }

def test_shopify_connection():
    """测试Shopify连接"""
    logger.info("开始诊断Shopify API连接问题")
    
    # 打印配置信息（屏蔽敏感数据）
    config = get_shopify_config()
    logger.info("\n配置检查:")
    logger.info(f"  API Key: {'已设置' if config['api_key'] else '未设置'}")
    logger.info(f"  API Secret: {'已设置' if config['api_secret'] else '未设置'}")
    logger.info(f"  Store URL: {'已设置: ' + config['store_url'] if config['store_url'] else '未设置'}")
    logger.info(f"  Access Token: {'已设置' if config['access_token'] else '未设置'}")
    
    # 验证URL格式
    if config['store_url'] and not config['store_url'].endswith('.myshopify.com'):
        logger.warning("警告: Store URL格式可能不正确，应该以 '.myshopify.com' 结尾")
    
    # 检查配置完整性
    if not all([config['api_key'], config['api_secret'], config['store_url'], config['access_token']]):
        logger.error("错误: 配置不完整，无法继续测试")
        return False
    
    # 尝试设置会话
    logger.info("\n尝试设置Shopify会话...")
    try:
        shopify.Session.setup(api_key=config['api_key'], secret=config['api_secret'])
        logger.info("  ✓ Session.setup 成功")
        
        # 创建会话
        session = shopify.Session(config['store_url'], "2023-10", config['access_token'])
        logger.info("  ✓ 创建Session成功")
        
        # 激活会话
        shopify.ShopifyResource.activate_session(session)
        logger.info("  ✓ 激活会话成功")
        
        # 测试连接
        logger.info("\n尝试获取商店信息...")
        try:
            shop = shopify.Shop.current()
            logger.info(f"  ✓ 成功获取商店信息: {shop.name}")
            logger.info(f"  ✓ 商店URL: {shop.myshopify_domain}")
            logger.info(f"  ✓ 商店邮箱: {shop.customer_email}")
        except Exception as shop_error:
            logger.error(f"  ✗ 获取商店信息失败: {shop_error}")
            return False
        
        # 尝试获取产品
        logger.info("\n尝试获取产品列表...")
        try:
            products = shopify.Product.find(limit=5)
            logger.info(f"  ✓ 获取产品成功，共 {len(products)} 个产品")
            
            # 显示产品信息
            for i, product in enumerate(products, 1):
                logger.info(f"  产品 {i}:")
                logger.info(f"    ID: {product.id}")
                logger.info(f"    标题: {product.title}")
                logger.info(f"    状态: {product.status}")
                
        except Exception as product_error:
            logger.error(f"  ✗ 获取产品失败: {product_error}")
            import traceback
            traceback.print_exc()
            return False
        
        return True
        
    except Exception as e:
        logger.error(f"  ✗ 设置Shopify会话失败: {e}")
        import traceback
        traceback.print_exc()
        return False
    finally:
        # 清理会话
        try:
            shopify.ShopifyResource.clear_session()
            logger.info("  ✓ 已清理会话")
        except:
            pass

if __name__ == "__main__":
    logger.info("=== Shopify API连接诊断工具 ===")
    success = test_shopify_connection()
    
    if success:
        logger.info("\n✓ 连接测试成功!")
    else:
        logger.info("\n✗ 连接测试失败，请检查上述错误信息")